package com.rpframework.module.common.spring.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rpframework.core.json.ServletThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

/**
 * JSON实例化默认
 * Created by jump on 2016/8/15.
 */
public class MappingJackson2HttpMessageConverter extends org.springframework.http.converter.json.MappingJackson2HttpMessageConverter {
    /**
     * Construct a new {@link org.springframework.http.converter.json.MappingJackson2HttpMessageConverter} using default configuration
     * provided by {@link Jackson2ObjectMapperBuilder}.
     */
    public MappingJackson2HttpMessageConverter() {
        this(Jackson2ObjectMapperBuilder.json().build());
    }

    /**
     * Construct a new {@link org.springframework.http.converter.json.MappingJackson2HttpMessageConverter} with a custom {@link ObjectMapper}.
     * You can use {@link Jackson2ObjectMapperBuilder} to build it easily.
     *
     * @see Jackson2ObjectMapperBuilder#json()
     */
    private MappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
        super(objectMapper);
    }

    @Override
    protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
        String callbackParam = ServletThreadLocal.getCallbackParam();
        if (!StringUtils.isBlank(callbackParam)) {
            generator.writeRaw(callbackParam + "(");
        }
    }

    @Override
    protected void writeSuffix(JsonGenerator generator, Object object) throws IOException {
        String callbackParam = ServletThreadLocal.getCallbackParam();
        if (!StringUtils.isBlank(callbackParam)) {
            generator.writeRaw(")");
        }
    }
}
